/**
 * 
 */
package com.jdy.haoduoai.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.OnColorChangedListener;
import com.jdy.haoduoai.intface.OnLightSwitchToggleListener;
import com.jdy.haoduoai.intface.OnLightnessChangedListener;
import com.jdy.haoduoai.model.ImUserSig;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

//import com.jdy.haoduoai.R;

/**
 * @author zp 2016-11-14 上午11:05:54
 */
public class BreathLightActivity extends BaseActivity implements
    OnClickListener, OnDataReceivedListener {

  @InjectView(id = R.id.white_colorful_layout, click = true)
  private RelativeLayout mWhiteColorLayout;

  // true for white ,false for colorful
  private final boolean mWhite = true;

  @InjectView(id = R.id.breath_mode_cb, click = true)
  private CheckBox mBreathModeCb;

  @InjectView(id = R.id.switch_cb, click = true)
  private CheckBox mSwitchCb;

  @InjectView(id = R.id.special_effect_layout)
  private LinearLayout mBottomLayout;

  @InjectView(id = R.id.center_palette_img)
  private ImageView mCenterPalette;

  @InjectView(id = R.id.on_off_img)
  private ImageView mOnOffImg;

  @InjectView(id = R.id.lightness_img)
  private ImageView mLightnessImg;

  // private GradientDrawable bgShape;

  @InjectView(id = R.id.root_layout)
  private RelativeLayout mRootLayout;

  @InjectView(id = R.id.brightness_seekbar)
  private SeekBar mBrightnessSeekBar;

  @InjectView(id = R.id.color_picker)
  private com.jdy.haoduoai.view.ColorPickerView mColorPicker;

  private int mPickedColor = 0xffffff;

  @InjectView(id = R.id.breath_switch)
  private com.jdy.haoduoai.view.BreathLightSwitch mBreathSwitch;
  @InjectView(id = R.id.lightness_controller)
  private com.jdy.haoduoai.view.LightnessController mLightnessController;

  private Bitmap PALETTE_BITMAP;
  private final static int FIXED_INSET = 105;
  private float initPickerAngle = 0;
  private ImUserSig mUserSigWrapper;
  private LeUser mLeUser;

  private static final String TAG = BreathLightActivity.class.getSimpleName();

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.breath_light_layout);

    setTitle("设置呼吸灯");

    mLeUser = ((LeXiaoXiaoBanApp) this.getApplication()).getUser();

    checkUserImSig();

    adjustMetrics();

    mRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener() {
          @Override
          public void onGlobalLayout() {
            mRootLayout.getViewTreeObserver()
                .removeGlobalOnLayoutListener(this);

            mColorPicker.setVisibility(View.GONE);

            PALETTE_BITMAP = loadBitmapFromView(mRootLayout);

            mColorPicker.setVisibility(View.VISIBLE);

            initStartupColor();
          }
        });

    mBreathSwitch
        .setOnLightSwitchToggleListener(new OnLightSwitchToggleListener() {

          @Override
          public void OnLightSwitchToggle(boolean switchOff) {
            // TODO Auto-generated method stub
            // toastShow("Current state:" + switchOff);
            if (switchOff == true) {
              sendBreathLightColor(0, 0, 0);
            }
          }
        });

    mLightnessController
        .setOnLightnessChangedListener(new OnLightnessChangedListener() {

          @Override
          public void onLightnessChanged(float start, float end,
              boolean increase, double current) {
            // TODO Auto-generated method stub
            // toastShow("Parameters are :" + start + "," + end + "," + increase
            // + "," + current + "!");
          }
        });

    // You should better to keep the minimum value of this seekbar to be at
    // least 1.
    mBrightnessSeekBar
        .setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

          @Override
          public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

          }

          @Override
          public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

          }

          @Override
          public void onProgressChanged(SeekBar seekBar, int progress,
              boolean fromUser) {
            // TODO Auto-generated method stub
            int brightness = progress;
            if (brightness <= 0)
              brightness = 1;
            int mode = 0;
            mBreathModeCb.setChecked(false);
            mSwitchCb.setChecked(true);
            sendBreathLightColor(mPickedColor, brightness, mode);

          }
        });

    mColorPicker.setColorPickerChangedListener(new OnColorChangedListener() {

      @Override
      public void onColorPickerPositionChanged(float x, float y, double degree) {

        Log.e(TAG, "x: ==>" + x + "y: ==>" + y);
        // TODO Auto-generated method stub
        Bitmap bitmap = PALETTE_BITMAP;

        int w = bitmap.getWidth() - 1;

        int h = bitmap.getHeight() - 1;

        int left = mColorPicker.getLeft() + mColorPicker.getPaddingLeft();

        int top = mColorPicker.getTop() + mColorPicker.getPaddingTop();

        Log.e(TAG, "left: ===>" + left + ", top :===>" + top);

        // Log.e(TAG, "w: ==>" + w + ",  h: ==>" + h);

        // float[] coords = getPointerCoords(mCenterPalette, x - left, y - top);

        int originalImageOffsetX = (int) x + left;

        int originalImageOffsetY = (int) y + top;

        Log.e(TAG, "originalImageOffsetX: ==>" + originalImageOffsetX
            + ",  originalImageOffsetY: ==>" + originalImageOffsetY);

        if (originalImageOffsetX > w || h < originalImageOffsetY
            || originalImageOffsetX < 0 || originalImageOffsetY < 0)
          return;
        else {
          // toastShow("Degree:" + degree);
          initPickerAngle = (float) degree;
          mPickedColor = bitmap.getPixel(originalImageOffsetX,
              originalImageOffsetY);
          int brightness = mBrightnessSeekBar.getProgress();
          if (brightness <= 0)
            brightness = 1;
          mBreathModeCb.setChecked(false);
          mSwitchCb.setChecked(true);
          sendBreathLightColor(mPickedColor, brightness, 0);
          // bgShape.setColor(mPickedColor);
        }
      }
    });

    mSwitchCb
        .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

          @Override
          public void onCheckedChanged(CompoundButton buttonView,
              boolean isChecked) {
            // TODO Auto-generated method stub
            if (isChecked) {
              mBreathModeCb.setEnabled(true);
            } else {
              mBreathModeCb.setChecked(false);
              mBreathModeCb.setEnabled(false);
            }
          }
        });
  }

  /**
   * Turn Off Mode: color 0xffffff，bright 0
   * 
   * @param color
   *          with prefix 0x
   * @param bright
   *          0 ~ 100
   * @param mode
   *          0 for color ,1 for breath
   */
  private void sendBreathLightColor(int color, int bright, int mode) {
    JSONObject jsonObject = new JSONObject();
    try {
      jsonObject.put("code", 202);
      jsonObject.put("act", "bln");
      JSONObject dataJo = new JSONObject();
      dataJo.put("color", 0xFFFFFF & color);
      dataJo.put("bright", bright);
      dataJo.put("type", mode);
      jsonObject.put("data", dataJo);
   //   if (mImHelper != null)
        SocketThreadManager.getInstance().send(jsonObject.toString());
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  private void requestBreathLightState() {
    JSONObject jsonObject = new JSONObject();
    try {
      jsonObject.put("code", 202);
      jsonObject.put("act", "getbln");
      jsonObject.put("data", "");
      //if (mImHelper != null)
        SocketThreadManager.getInstance().send(jsonObject.toString());
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  private void checkUserImSig() {
    String userSig = LePreference.getInstance().getString("usersig");
    if (Tools.isNotEmpty(userSig)) {
      mUserSigWrapper = JsonSerializer.getInstance().deserialize(userSig,
          ImUserSig.class);
    }

    SocketThreadManager.getInstance().setDataReceivedListener(this);

//    JSONObject jsonObject = new JSONObject();
//    try {
//      jsonObject.put("code", 202);
//      jsonObject.put("act", "connect");
//      jsonObject.put("data", mLeUser.id);
//      SocketThreadManager.getInstance().send(jsonObject.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    }

//    mImHelper = LeXiaoXiaoBanApp.getInstance().getImHelper();
//
//    if (!mImHelper.isLogin()) {
//      if (Tools.isNotEmpty(mUserSigWrapper)) {
//        mImHelper.init(LeXiaoXiaoBanApp.getAppContext(),
//            mUserSigWrapper.AccountType, mUserSigWrapper.SdkAppId, mLeUser.id,
//            mUserSigWrapper.Sig);
//        mImHelper.login();
//
//      } else {
//        getTlsUserSig();
//      }
//    } else {
//      LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
//      mImHelper.setOnDataReceivedListener(this);
//      mImHelper.connect(lb.id);
//
//      // {"code":"app","act":"connect","data":"手机号"}
//      JSONObject jsonObject = new JSONObject();
//      try {
//        jsonObject.put("code", "app");
//        jsonObject.put("act", "connect");
//        jsonObject.put("data", mLeUser.id);
//        mImHelper.send(jsonObject.toString());
//      } catch (JSONException e) {
//        e.printStackTrace();
//      }
//    }
  }

//  private void getTlsUserSig() {
//    new CustomAsyncTask(this, new IAsyncTask() {
//      @Override
//      public void onRecieveData(Activity activity, ResponseResult result) {
//        if (result.isSuccess()) {
//          mUserSigWrapper = JsonSerializer.getInstance().deserialize(
//              result.data, ImUserSig.class);
//
//          if (mUserSigWrapper != null) {
//            mImHelper.init(LeXiaoXiaoBanApp.getAppContext(),
//                mUserSigWrapper.AccountType, mUserSigWrapper.SdkAppId,
//                mLeUser.id, mUserSigWrapper.Sig);
//            LePreference.getInstance().save("usersig", result.data);
//            mImHelper.login();
//          }
//        } else {
//          if (Tools.isNotNullStr(result.data)) {
//            Toast.makeText(BreathLightActivity.this, result.data,
//                Toast.LENGTH_SHORT).show();
//          }
//        }
//      }
//
//      @SuppressWarnings("unused")
//      @Override
//      public ResponseResult doInbackground(Activity activity) {
//        HashMap<String, Object> param_ = new HashMap<String, Object>();
//
//        int uid = -1, volume = -1, minutes = -1;
//        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
//
//        if (lu == null) {
//          lu = Tools.restoreLeUser();
//        }
//
//        param_.put("user", lu.id);
//        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
//
//        return HttpUtils.startRequest(
//            HttpUtils.API_URL + HttpUtils.GET_TLS_SIG, param_,
//            HttpUtils.TAG_POST_REQUEST);
//
//      }
//    }).execute();
//  }

  @Override
  protected void onResume() {
    super.onResume();
    initPickerAngle = LePreference.getInstance().getFloat("init_picker_angle");
    mColorPicker.setInitAngle(initPickerAngle);
    requestBreathLightState();
  }

  @Override
  protected void onPause() {
    super.onPause();
    LePreference.getInstance().save("init_picker_angle", initPickerAngle);
  }

  /**
   * 
   */
  private void initStartupColor() {
    float x = mColorPicker.getStartPickerPositioin().x;

    float y = mColorPicker.getStartPickerPositioin().y;
    // TODO Auto-generated method stub
    Log.e(TAG, "x: ==>" + x + "y: ==>" + y);
    // TODO Auto-generated method stub
    Bitmap bitmap = PALETTE_BITMAP;

    int w = bitmap.getWidth() - 1;

    int h = bitmap.getHeight() - 1;

    int left = mColorPicker.getLeft() + mColorPicker.getPaddingLeft();

    int top = mColorPicker.getTop() + mColorPicker.getPaddingTop();

    Log.e(TAG, "left: ===>" + left + ", top :===>" + top);

    // Log.e(TAG, "w: ==>" + w + ",  h: ==>" + h);

    // float[] coords = getPointerCoords(mCenterPalette, x - left, y - top);

    int originalImageOffsetX = (int) x + left;

    int originalImageOffsetY = (int) y + top;

    Log.e(TAG, "originalImageOffsetX: ==>" + originalImageOffsetX
        + ",  originalImageOffsetY: ==>" + originalImageOffsetY);

    if (originalImageOffsetX > w || h < originalImageOffsetY
        || originalImageOffsetX < 0 || originalImageOffsetY < 0)
      return;
    // else
    // bgShape.setColor(bitmap.getPixel(originalImageOffsetX,
    // originalImageOffsetY));
  }

  public Bitmap loadBitmapFromView(View v) {

    int width = getWindow().getDecorView().getRootView().getWidth();

    int height = getWindow().getDecorView().getRootView().getHeight();

    Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    Canvas c = new Canvas(b);

    v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);

    v.draw(c);

    return b;
  }

  // final float[] getPointerCoords(ImageView view, float x, float y) {
  // final float[] coords = new float[] { x, y };
  // Matrix matrix = new Matrix();
  // view.getImageMatrix().invert(matrix);
  // // matrix.postTranslate(view.getScrollX(), view.getScrollY());
  // matrix.mapPoints(coords);
  // return coords;
  // }

  private void adjustMetrics() {

    float ratio = Tools.getPixelRatio(this);

    int height = (int) (ratio * 222);

    android.view.ViewGroup.LayoutParams params = mBottomLayout
        .getLayoutParams();

    params.height = height;

    mBottomLayout.setLayoutParams(params);

    android.view.ViewGroup.LayoutParams params2 = mCenterPalette
        .getLayoutParams();

    params2.width = (int) (ratio * 740);

    params2.height = (int) (ratio * 740);

    mCenterPalette.setLayoutParams(params2);

    MarginLayoutParams params3 = (MarginLayoutParams) mOnOffImg
        .getLayoutParams();

    params3.topMargin = (int) (ratio * 140);

    params3.leftMargin = (int) (ratio * 80);

    mOnOffImg.setLayoutParams(params3);

    MarginLayoutParams params4 = (MarginLayoutParams) mLightnessImg
        .getLayoutParams();

    params4.rightMargin = (int) (ratio * 100);

    params4.bottomMargin = (int) (ratio * 80);

    mLightnessImg.setLayoutParams(params4);

  }

  @Override
  public void onDestroy() {
    super.onDestroy();

  //  if (mImHelper != null) {
      SocketThreadManager.getInstance().removeDataReceivedListener(this);
   // }
  }

  /*
   * (non-Javadoc)
   * 
   * @see android.view.View.OnClickListener#onClick(android.view.View)
   */
  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.breath_mode_cb:
      if (mSwitchCb.isChecked()) {
        int brightness = mBrightnessSeekBar.getProgress();
        if (brightness <= 0)
          brightness = 1;
        int mode = -1;
        if (mBreathModeCb.isChecked())
          mode = 1;
        else
          mode = 0;
        sendBreathLightColor(mPickedColor, brightness, mode);
      } else {
        toastShow("开关没有打开!");
      }

      break;
    case R.id.switch_cb:
      int brightness = 1;
      int mode = -1;
      if (mBreathModeCb.isChecked())
        mode = 1;
      else
        mode = 0;

      if (mSwitchCb.isChecked()) {
        brightness = mBrightnessSeekBar.getProgress();
        if (brightness <= 0)
          brightness = 1;
      } else {
        brightness = 0;
      }

      sendBreathLightColor(0xffffff, brightness, mode);
      break;
    default:
      break;
    }
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * com.jdy.haoduoai.util.OnDataReceivedListener#onDataReceived(java.lang
   * .String)
   */
  @Override
  public void onDataReceived(final String data) {


    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        if (Tools.isNotEmpty(data)) {
          try {
            JSONObject jsonData = new JSONObject(data.toString());
            if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("act")) {
              if (jsonData.getString("act").contains("blnstatus")) {
                String realData = jsonData.getString("data");
                if (Tools.isNotEmpty(realData)) {
                  JSONObject jo = new JSONObject(realData);
                  mPickedColor = jo.getInt("color");
                  int brightness = jo.getInt("bright");
                  if (brightness == 0) {
                    mSwitchCb.setChecked(false);
                  } else {
                    mSwitchCb.setChecked(true);
                  }

                  mBrightnessSeekBar.setProgress(brightness);
                  int mode = jo.getInt("type");
                  if (mode == 1) {
                    mBreathModeCb.setChecked(true);
                  } else if (mode == 0) {
                    mBreathModeCb.setChecked(false);
                  }
                }
              } else if (jsonData.getString("act").contains("Device_Login")) {
                LeConfig.isDeviceConnect = true;
              } else if (jsonData.getString("act").contains("Device_Logout")) {
                LeConfig.isDeviceConnect = false;
              } else if (jsonData.getString("act").contains(
                      "Device_APP_Connection_Switched")) {
                // Intent logoutIntent = new Intent(
                // "com.jdy.haoduoai.activity.logout");
                // sendBroadcast(logoutIntent);
                //
                // LeConfig.isLogin = false;
                // LeConfig.isDeviceActivated = false;
                // LeConfig.isDeviceBinded = false;
                // LeConfig.isInfoFilled = false;
                // LeConfig.isDeviceConnect = false;
                //
                // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
                // getApplicationContext()).setTitle("下线通知")
                // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                //
                // @Override
                // public void onClick(DialogInterface dialog, int which) {
                // dialog.dismiss();
                // }
                // });
                // final CustomOneBtnDialog cd = cdb.create();
                // cd.getWindow()
                // .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                // cd.setOnDismissListener(new OnDismissListener() {
                //
                // @Override
                // public void onDismiss(DialogInterface dialog) {
                // Intent toActivityIntent = new Intent(BreathLightActivity.this,
                // LoginActivity.class);
                // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                // startActivity(toActivityIntent);
                // finish();
                // }
                // });
                // cd.show();
              }
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }
    });


  }
}
